package com.myh.testlogin.common.exception;

import cn.hutool.extra.spring.SpringUtil;
import com.myh.testlogin.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 200 Assert异常
     * @param e
     * @return
     */
    @ResponseStatus(org.springframework.http.HttpStatus.OK)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        System.out.println("IllegalArgumentException");
        log.warn("Assert异常：----------------{}----msg={}", e, e.getMessage());
        return Result.ok(201,e.getMessage()).put("data",null);
    }

    /**
     * 400
     * 参数错误 比如期望username 但是传入的是username1
     * @param e
     * @return
     */
    @ResponseStatus(org.springframework.http.HttpStatus.OK)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e) {
        //获取错误消息
        log.warn("实体校验异常：----------------{}", e.getBindingResult().getFieldErrors());
        BindingResult bindingResult = e.getBindingResult();
        //错误消息的全部字段
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        HashMap<String, Object> errorMsg = new HashMap<>();
        for (FieldError o : fieldErrors) {
            //消息的字段和错误提示
            errorMsg.put(o.getField(),o.getDefaultMessage());
        }
        return Result.error(HttpStatus.SC_BAD_REQUEST,"错误参数").put("data",errorMsg);
    }

    /**400
     * 传入参数转化异常
     * @param e
     * @return
     */
    @ResponseStatus(org.springframework.http.HttpStatus.OK)
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result handler(HttpMessageNotReadableException e) {
        log.warn("参数类型转化异常：----------------{}----msg={}", e, e.getMessage());
        return Result.error(HttpStatus.SC_BAD_REQUEST,"参数异常").put("data",null);
    }
}
